package com.cwz.security.aspect;

import com.cwz.core.constant.SecurityConstants;
import com.cwz.core.exception.inner.InnerAuthException;
import com.cwz.core.utils.servle.ServletUtils;
import com.cwz.core.utils.string.StringUtils;
import com.cwz.security.annotation.InnerAuth;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: w-demo
 * @description: 内部服务调用验证处理（用于 feign 接口的调用）
 * @author: Wen
 **/
@Aspect
@Component
public class InnerAuthAspect implements Ordered {

	@Around("@annotation(innerAuth)")
	public Object innerAround(ProceedingJoinPoint point, InnerAuth innerAuth) throws Throwable {
		HttpServletRequest request = ServletUtils.getRequest();
		String source = request.getHeader(SecurityConstants.FROM_SOURCE);
		// 内部请求验证
		if (!StringUtils.equals(SecurityConstants.INNER, source)) {
			throw new InnerAuthException("没有内部访问权限，不允许访问");
		}
		String userId = request.getHeader(SecurityConstants.DETAILS_USER_ID);
		String username = request.getHeader(SecurityConstants.DETAILS_USERNAME);
		// 用户信息验证
		if (innerAuth.isUser() && (StringUtils.isEmpty(userId) || StringUtils.isEmpty(username))) {
			throw new InnerAuthException("没有设置用户信息，不允许访问");
		}
		return point.proceed();
	}

	/**
	 * @Description: 确保在权限认证 aop 执行前执行
	 * @Author: Wen
	 * @return: int
	 **/
	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE + 1;
	}
}
